
//获取操作人的姓名及ID
var loginData=JSON.parse(web.readCookie("loginData"));
var service_name = loginData.user.username;
var service_id = loginData.user.user_ID;
// 重置功能
$('#resetbtn').click(function () {
    document.getElementById("form-search").reset();
    // $('#inquiry_status').val('');
    //$("#submitBtn").trigger('click');
})
var dataSource = new Array();
//table的数据源
var table; //table对象
dataSource = [];
// 通过查询获得数据
function getList(){
    var datas={}
    if($("#selfMentionPointNames").text()==""){
        datas={
            page_size: 20,
            page_num: 1,
            order_id: $("#order_id").val(),
            platform: $("#platform").val(),
            customer_name: $("#customer_name").val(),
            deal_status: $("#deal_status").val(),
            created_at_begin: $("#timemin").val(),
            created_at_end: $("#timemax").val(),
            companys_ids:sessionStorage.getItem("organizationWarehouse"),//公司对应的发货仓id
            warehouse_ids:sessionStorage.getItem("regions"),//仓库权限串
            belong_groupIds:sessionStorage.getItem("companys"),//销售归属权限串
            sales_manager_ids:sessionStorage.getItem("personnels"),//销售经理权限串
            sent_type:$("#sent_type").val(),//配送类型
            parent_warehouse_id:$("#shippingWarehouse option:selected").val(),
            warehouse_id:$("#selfMentionPointNames").text(),
            paid_type: $("#payWay").val(), //支付方式
            apply_role:$("#apply_role").val()

        }
    }else {
        datas={
            page_size: 20,
            page_num: 1,
            order_id: $("#order_id").val(),
            platform: $("#platform").val(),
            customer_name: $("#customer_name").val(),
            deal_status: $("#deal_status").val(),
            created_at_begin: $("#timemin").val(),
            created_at_end: $("#timemax").val(),
            companys_ids:sessionStorage.getItem("organizationWarehouse"),//公司对应的发货仓id
            warehouse_ids:sessionStorage.getItem("regions"),//仓库权限串
            belong_groupIds:sessionStorage.getItem("companys"),//销售归属权限串
            sales_manager_ids:sessionStorage.getItem("personnels"),//销售经理权限串
            sent_type:50,//配送类型
            parent_warehouse_id:$("#shippingWarehouse option:selected").val(),
            warehouse_id:$("#selfMentionPointNames").text(),
            paid_type: $("#payWay").val(), //支付方式
            apply_role:$("#apply_role").val()
        }
    }
    $.ajax({
        contentType: 'application/json',
        url: root.orderInter.order_cancel_apply,
        //url: 'http://192.168.65.116:7090/aorder/ordercancleapply/listOrderCancleApply',
        cache: false, //禁用缓存
        type: "POST",
        data: JSON.stringify(datas),
        success: function(data) {

            sessionStorage.setItem("dealstatus1",'')
            sessionStorage.setItem("dealstatus2",'')
            goodsList(data);
            totalPage = data.data.totalPage;
            $('.M-box3').pagination({
                pageCount: totalPage,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function(api) {
                    var datas2={}
                    if($("#selfMentionPointNames").text()==""){
                        var datas2={
                            page_size: 20,
                            page_num: api.getCurrent(),
                            order_id: $("#order_id").val(),
                            platform: $("#platform").val(),
                            customer_name: $("#customer_name").val(),
                            deal_status: $("#deal_status").val(),
                            created_at_begin: $("#timemin").val(),
                            created_at_end: $("#timemax").val(),
                            companys_ids:sessionStorage.getItem("organizationWarehouse"),//公司对应的发货仓id
                            warehouse_ids:sessionStorage.getItem("regions"),//仓库权限串
                            belong_groupIds:sessionStorage.getItem("companys"),//销售归属权限串
                            sales_manager_ids:sessionStorage.getItem("personnels"),//销售经理权限串
                            sent_type:$("#sent_type").val(),//配送类型
                            parent_warehouse_id:$("#shippingWarehouse option:selected").val(),
                            warehouse_id:$("#selfMentionPointNames").text(),
                            paid_type: $("#payWay").val(), //支付方式
                            apply_role:$("#apply_role").val()
                        }
                    }else {
                        datas2={
                            page_size: 20,
                            page_num: api.getCurrent(),
                            order_id: $("#order_id").val(),
                            platform: $("#platform").val(),
                            customer_name: $("#customer_name").val(),
                            deal_status: $("#deal_status").val(),
                            created_at_begin: $("#timemin").val(),
                            created_at_end: $("#timemax").val(),
                            companys_ids:sessionStorage.getItem("organizationWarehouse"),//公司对应的发货仓id
                            warehouse_ids:sessionStorage.getItem("regions"),//仓库权限串
                            belong_groupIds:sessionStorage.getItem("companys"),//销售归属权限串
                            sales_manager_ids:sessionStorage.getItem("personnels"),//销售经理权限串
                            sent_type:50,//配送类型
                            parent_warehouse_id:$("#shippingWarehouse option:selected").val(),
                            warehouse_id:$("#selfMentionPointNames").text(),
                            paid_type: $("#payWay").val(), //支付方式
                            apply_role:$("#apply_role").val()
                        }
                    }
                    console.log(api.getCurrent());
                    $.ajax({
                        contentType: 'application/json',
                        url: root.orderInter.order_cancel_apply,
                        //url: 'http://localhost:7090/aorder/ordercancleapply/listOrderCancleApply',
                        cache: false, //禁用缓存
                        type: "POST",
                        data: JSON.stringify(datas2),
                        success: function(data) {
                            goodsList(data);
                        }
                    });
                }
            });
        }
    });
}

function goodsList(data) {
    sessionStorage.setItem("authorizedUsers", JSON.stringify(data));
    dataSource.splice(0, dataSource.length);//清空数组

    if (data.data.result != null) {
        var datashu = data.data.startIndex + 1;
        $.each(data.data.result, function (i, field) {
            var datashus = datashu++
            var rowData = new Array();
            rowData.push(field.order_id);
            rowData.push(field.platform);
            rowData.push(field.customer_name);
            rowData.push(field.created_at);
            rowData.push(field.order_created_at);
            /*rowData.push(field.final_paid_type);*/
            rowData.push(field.paid_type);
            rowData.push(field.paid_amount);
            rowData.push(field.deal_status);
            rowData.push(field.id);
            rowData.push(field.sent_type);
            rowData.push(datashus);
            rowData.push(field.products);//商品信息
            dataSource.push(rowData);
        });
    }

    initDataTable(dataSource);
}
var paidtypeall={
    '1001': "在线支付", '1002': "支付宝支付", '1003': "微信支付", '1101': "货到付款", '1102': "货到付款-现金", '1103': "货到付款-pos机", '1201': "账期支付",
    '1301': "银行转账", '1401': "银行汇票", '1601': "积分支付", '1701': "门店付款"
}
var senttypeall={
    '10': "快递", '20': "快运", '21': "快运", '30': "专车包车", '40': "鑫方盛物流", '50': "上门自提", '52': "配送客户自提",
}
function initDataTable(dataSource) {

    var outHtml = '';
    for(var i=0;i<dataSource.length;i++){
        var curData= dataSource[i];

        var platFormStr = ""
        switch (curData[1]) {
            case 10:
                platFormStr ="普通平台";
                break;
            case 20:
                platFormStr = "签约平台";
                break;
            case 40:
                platFormStr = "对接平台";
                break;
        }
        var inquiryStr = '';
        var productData = curData[11];
        var productStr = '';
        var curProLen = productData ? productData.length : 1;

        var receivernames=""
        if (curData[4]==undefined || curData[4]==null){
            receivernames=""
        }else{
            receivernames=curData[4].receiver_name
        }
        var state = "";
        switch (curData[7]) {
            case 10:
                state ="待处理";
                break;
            case 20:
                state = "处理中";
                break;
            case 30:
                state = "已处理";
                break;
            case 40:
                state = "已关闭";
                break;

        }


        inquiryStr+= '<td width="115" rowspan="'+curProLen+'">'+isUndefined(curData[2])+'</td>'+
            '<td width="70" rowspan="'+curProLen+'">'+timeIsDefault(curData[3])+'</td>'+
            '<td width="70" rowspan="'+curProLen+'">'+paidtypeall[curData[5]]+'</td>'+
            '<td width="70" rowspan="'+curProLen+'">'+senttypeall[curData[9]]+'</td>'+
            '<td width="70" rowspan="'+curProLen+'">'+(curData[6]).toFixed(2)+'</td>'+
            '<td width="70" rowspan="'+curProLen+'">'+state+'</td>'+
            '<td width="100" rowspan="'+curProLen+'"><span class="powerButton 112"><a onclick="orderdetail(\'取消订单申请详情\',\'cancelOrderDetails.html\',\''+curData[0]+'\',\''+curData[8]+'\',1)">查看详情</a></span></td>';


        var showMoreHtml = '';
        if(curProLen>3){
            showMoreHtml = '<div class="list_more " onclick="showMore(this);"><a href="javascript:void(0);">查询了<span id="list_length">'+curProLen+'</span>件商品  <span id="operText">更多</span><i class="icon"></i></a></div>'
        }
        if(productData && productData.length>0){
            for(var j=0;j<productData.length;j++){
                var curPro = productData[j];
                if(j!=0){
                    inquiryStr = '';
                }

                var isHideClass = '';
                if(j>=3){
                    isHideClass = 'moretr hide';
                }

                productStr +='<tr class="'+isHideClass+'">'+
                    '<td width="75" rowspan="1"><img style="width:60px;height:60px;" src="' + imgSize(curPro.product_pic) + '"/></td>'+
                    '<td width="135" rowspan="1"><div>' + curPro.sku_code + '</div><div>' + curPro.product_name + '</div><div>' + curPro.color + '</div><div>' + curPro.sku_info + '</div></td>'+
                    '<td width="75" rowspan="1"><span>X</span>' + curPro.buyyer_count + '' + curPro.unit_name + '</td>'+  inquiryStr +
                    '</tr>';

            }


        }else{
            productStr +='<tr>'+
                '<td width="75" rowspan="1"></td>'+
                '<td width="135" rowspan="1"></td>'+
                '<td width="75" rowspan="1"></td>'+  inquiryStr +
                '</tr>';
        }

        outHtml+= '<div class="orer_item"><div class="list_box list_over">'+
            '<div class="title">'+
            '<span>订单号：'+isUndefined(curData[0])+'</span>'+
            '<span>下单时间：'+timeIsDefault(curData[4])+'</span>'+
            '<span>订单来源：'+platFormStr+'</span>'+
            '</div>'+
            '<table style="width:100%;" class="table table-border table-bg table-sort list_box_table"><tbody>'+productStr+'</tbody></table></div>'+showMoreHtml+'</div>';
    }

    $('#orderList').empty().append(outHtml);
        //权限控制函数
        power()

}
function isUndefined(dt){
    var str = dt ? dt : '';
    return str;
}
function timeIsDefault(tm){
    var str = tm == '1000-01-01 00:00:00' ? '' : tm;
    return str;
}
//更多
function showMore(dom, length,status) {
    var curDom = $(dom);
    var curTr = curDom.parents('.orer_item').find('.moretr');
    if(curTr.eq(0).hasClass('hide')){
        curTr.removeClass('hide');
        curDom.find('#operText').html('收起');
    }else{
        curTr.addClass('hide');
        curDom.find('#operText').html('更多');
    }

}
/*跳转订单详情*/
function orderdetail(title,url,data,pid,type){
    sessionStorage.setItem("orderIId",data);
    sessionStorage.setItem("pid",pid);
    sessionStorage.setItem("type",type);

    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}
//弹框跳转
var dealstatus1= sessionStorage.getItem("dealstatus1")//待处理
var dealstatus2= sessionStorage.getItem("dealstatus2")//处理中
if(dealstatus1==10){
    $('#deal_status').val(dealstatus1)
    getList()
}
if(dealstatus2==20){
    $('#deal_status').val(dealstatus2)
    getList()
}

//自提点
myFunctions()
function myFunctions(){
    $("#selfMentionPointNames").val("")
    var user_data = {
        pWarehouseCode:$("#shippingWarehouse option:selected").val()

    }
    var succCallBack = function (data, status, response) {
        console.log(data)
        if(data.errorCode=="0"){
            var jsonObj =data.data;
            if(jsonObj=="" ||$("#shippingWarehouse option:selected").val()==""){
                $("#tuan").html("<li>无数据</li> ");
            }else {
                console.log(jsonObj)

                var optionstring = "";
                for (var  i= 0; i < jsonObj.length; i++) {
                    optionstring += "<li onclick='relation("+ jsonObj[i].warehouseCode+",\""+jsonObj[i].selfMentionPointName+"\")' data-align=\"" + jsonObj[i].warehouseCode + "\" > " + jsonObj[i].selfMentionPointName + "</li>";
                }
                $("#tuan").html(optionstring);
                console.log(jsonObj)
            }
        }else{
            $("#tuan").html("<li>无数据</li> ");
        }
    }
    web.doAjax(root.orderInter.queryStoreAddressByPwarehouseCode,'post',user_data, succCallBack);

}
//取光标
$("#selfMentionPointNames").focus(function () {
    $("#tuan").show()
});
$(document).bind("click",function(e){
    //id为menu的是菜单，id为open的是打开菜单的按钮
    if($(e.target).closest("#tuan").length == 0 && $(e.target).closest("#selfMentionPointNames").length == 0){
        //点击id为menu之外且id不是不是open，则触发
        $("#tuan").hide()
    }
})
function relation(id,ce) {
    $("#selfMentionPointNames").val(ce).text(id)
    $("#tuan").hide()
    console.log($("#selfMentionPointNames").text())
}